var maxOffsetY = 0;
var activeButton = null;
// Capture mouse clicks on the page so any active button can be
// deactivated.

/*
 * El siguiente segmento esta basado en --
 *  Prototype JavaScript framework, version 1.6.0.2
 *  (c) 2005-2008 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

 var Prototype = {
  Version: '1.6.0.2',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div').__proto__ &&
      document.createElement('div').__proto__ !==
        document.createElement('form').__proto__
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) {return x}
};

/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({toString: true}).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value, value = Object.extend((function(m) {
          return function() {return ancestor[m].apply(this, arguments)};
        })(property).wrap(method), {
          valueOf:  function() {return method},
          toString: function() {return method.toString()}
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (Object.isUndefined(object)) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : String(object);
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown':return;
      case 'boolean':return object.toString();
    }

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (Object.isElement(object)) return;

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (!Object.isUndefined(value))
        results.push(property.toJSON() + ': ' + value);
    }

    return '{' + results.join(', ') + '}';
  },

  toQueryString: function(object) {
    return $H(object).toQueryString();
  },

  toHTML: function(object) {
    return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({ }, object);
  },

  isElement: function(object) {
    return object && object.nodeType == 1;
  },

  isArray: function(object) {
    return object != null && typeof object == "object" &&
      'splice' in object && 'join' in object;
  },

  isHash: function(object) {
    return object instanceof Hash;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  },

  isNumber: function(object) {
    return typeof object == "number";
  },

  isUndefined: function(object) {
    return typeof object == "undefined";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat($A(arguments)));
    };
  }
});

Function.prototype.defer = Function.prototype.delay.curry(0.01);

var $break = { };

var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.collect(iterator, context);
  },

  all: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = true;
    this.each(function(value, index) {
      result = result && !!iterator(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function(iterator, context) {
    iterator = iterator.bind(context);
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(filter, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];

    if (Object.isString(filter))
      filter = new RegExp(filter);

    this.each(function(value, index) {
      if (filter.match(value))
        results.push(iterator(value, index));
    });
    return results;
  },

  include: function(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = Object.isUndefined(fillWith) ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var trues = [], falses = [];
    this.each(function(value, index) {
      (iterator(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator, context) {
    iterator = iterator.bind(context);
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (Object.isFunction(args.last()))
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
};

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
    if (!iterable) return [];
    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
}

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(Object.isArray(value) ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  intersect: function(array) {
    return this.uniq().findAll(function(item) {
      return array.detect(function(value) {return item === value});
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (!Object.isUndefined(value)) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
};

Array.prototype.toArray = Array.prototype.clone;

function $H(object) {
  return new Hash(object);
};


var Hash = Class.create(Enumerable, (function() {

  function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

  return {
    initialize: function(object) {
      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
    },

    _each: function(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    },

    set: function(key, value) {
      return this._object[key] = value;
    },

    get: function(key) {
      return this._object[key];
    },

    unset: function(key) {
      var value = this._object[key];
      delete this._object[key];
      return value;
    },

    toObject: function() {
      return Object.clone(this._object);
    },

    keys: function() {
      return this.pluck('key');
    },

    values: function() {
      return this.pluck('value');
    },

    index: function(value) {
      var match = this.detect(function(pair) {
        return pair.value === value;
      });
      return match && match.key;
    },

    merge: function(object) {
      return this.clone().update(object);
    },

    update: function(object) {
      return new Hash(object).inject(this, function(result, pair) {
        result.set(pair.key, pair.value);
        return result;
      });
    },

    toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

    inspect: function() {
      return '#Hash:{' + this.map(function(pair) {
        return pair.map(Object.inspect).join(': ');
      }).join(', ') + '}';
    },

    toJSON: function() {
      return Object.toJSON(this.toObject());
    },

    clone: function() {
      return new Hash(this);
    }
  }
})());

Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;


/*
 * Fin del segmento basado en Prototype JavaScript framework, version 1.6.0.2
 *  (c) 2005-2008 Sam Stephenson
 */ 

if (Prototype.Browser.IE)
    document.onmousedown = pageMousedown;
else
    document.addEventListener("mousedown", pageMousedown, true);

function importXML() {
    if (window.ActiveXObject) {
        xmlDoc =new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(xmlText);
        Procesar();
    }
    // code for Mozilla, Firefox, Opera, etc.
    else
    {
        var parser=new DOMParser();
        xmlDoc=parser.parseFromString(xmlText,"text/xml");
        Procesar();
    }
}

function Procesar()
{  
    var menus = xmlDoc.getElementsByTagName('Menu');
    if (menus.length <= 0) return 0;
    var cacheOfDivs = {};
    for (var i = 0; i < menus.length ;i++) {
        var contenedor = document.createElement('DIV');
        var div = document.createElement('DIV');
        contenedor.appendChild(div);
        var temp = document.getElementById("dest");
        var padre = temp.parentNode;
        contenedor.style.cssText = temp.style.cssText;
        contenedor.id="dest";
        padre.replaceChild(contenedor,temp);
        div.className="menuBar";
        var menuItem = menus[i].getElementsByTagName('Menu.menu_item');
        for (var j = 0; j < menuItem.length; j++) {
            var padreId = menuItem[j].getElementsByTagName('parent_id');
            var id = menuItem[j].getElementsByTagName('id');

            var desc = menuItem[j].getElementsByTagName('name');
            var objeto = menuItem[j].getElementsByTagName('url');
            if (!padreId[0] || !id[0] || !desc[0] || !objeto[0]) {
                alert("XML mal formado, abortando");
                return -1;
            }
            var a = document.createElement("A");
            if (!padreId[0].firstChild) { // es un nodo padre
                a.innerHTML = desc[0].firstChild.nodeValue;
                a.className = "menuButton";
                a.padre = id[0].firstChild.nodeValue;
                if (objeto[0].firstChild) { // soy una accion directa
                    a.href=objeto[0].firstChild.nodeValue;
                    a.style.cursor="hand";
                    a.onmouseover=function() {buttonClick(this, this.padre+"Menu");buttonMouseover(this, this.padre+"Menu");};
                }
                else { // soy el elemento superior de un menu
                    a.onclick=function() {buttonClick(this, this.padre+"Menu");buttonMouseover(this, this.padre+"Menu");return false;};
                    a.onmouseover=function(){barMouseOver(this,this.padre+"Menu");};
                    a.href="#";
                }
                div.appendChild(a);
            }
            else { // es un nodo hijo
                a.className="menuItem";
                a.padre = id[0].firstChild.nodeValue;
                if (!objeto[0].firstChild) { // tengo hijos
                    if (Prototype.Browser.IE || Prototype.Browser.Opera) {
                        a.onmouseover = function() {menuItemMouseover(event, this.padre + "Menu");};
                    }
                    else {
                        a.onmouseover = function(event) {menuItemMouseover(event, this.padre + "Menu");};
                    }
                    a.onclick = function() {return false;};
                    a.href="index.jsp";
                    var span1 = document.createElement("SPAN");
                    span1.className="menuItemText";
                    span1.innerHTML = desc[0].firstChild.nodeValue;
                    var span2 = document.createElement("SPAN");
                    span2.className="menuItemArrow";
                    span2.innerHTML = "&#9654;";
                    a.appendChild(span1);
                    a.appendChild(span2);
                }
                else { // no tengo hijos
                    a.innerHTML = desc[0].firstChild.nodeValue;
                    a.href=objeto[0].firstChild.nodeValue;
                    //crear la funcion menuLeafMouseOver y sacar de buttonClick lo que agregue y ponerlo en esta
                    if (Prototype.Browser.IE || Prototype.Browser.Opera) {
                        a.onmouseover = function() {menuLeafMouseOver(event, this.padre + "Menu");};
                    }
                    else {
                        a.onmouseover = function(event) {menuLeafMouseOver(event, this.padre + "Menu");};
                    }
                }
                var destino = document.getElementById(padreId[0].firstChild.nodeValue+'Menu');
                if (destino) {
                    destino.appendChild(a);
                }
                else {
                    destino = document.createElement('DIV');
                    destino.className="menu";
                    destino.id = padreId[0].firstChild.nodeValue + 'Menu';
                    if (Prototype.Browser.IE || Prototype.Browser.Opera) {
                        destino.onmouseover = function() {menuMouseover(event, this);};
                    }
                    else {
                        destino.onmouseover = function(event) {menuMouseover(event, this);};
                    }
                    //Aca es el asunto, aca es que los tengo que insertar en orden
                    contenedor.appendChild(destino);
                    cacheOfDivs[destino.id] = destino;
                    if (cacheOfDivs[id[0].firstChild.nodeValue + 'Menu']) {
                        child = cacheOfDivs[id[0].firstChild.nodeValue + 'Menu']
                        contenedor.removeChild(child);
                        //Si hubiera mas de un nivel de sub menus tendria que hacer esta parte recursiva
                        contenedor.appendChild(child);
                    }
                    var iframe = document.createElement('IFRAME');
                    iframe.style.zIndex= -1;
                    iframe.style.width = "0px";
                    iframe.style.height = "0px";
                    iframe.src = "";
                    iframe.frameBorder = 0;
                    iframe.scrolling = "no";
                    iframe.id = padreId[0].firstChild.nodeValue + 'Frame';
                    destino.appendChild(iframe);
                    destino.appendChild(a);
                }
            }
        }
        for (var k = 0; k < contenedor.childNodes.length; k++) {
            var child = contenedor.childNodes[k];
            if (child.tagName == "DIV" && child.className=="menuBar") {
                var as = child.getElementsByTagName("A"); // estos son los padres
                for (var l = 0; l < as.length; l++) {
                    maxOffsetY = Math.max(maxOffsetY ,getPageOffsetTop(as[l]) + as[l].offsetHeight);
                }
            }
        }
    }
    return 0;
}
//esto podria estar en un archivo comun para el menu horizontal y vertical
function crearMenu() {
    try {
        importXML();
    }
    catch (e) {
        alert(e.message);
    }
}

function pageMousedown(event) {
    var el;
    if (activeButton == null)
      return;

    if (Prototype.Browser.IE)
      el = window.event.srcElement;
    else
      el = (event.target.tagName ? event.target : event.target.parentNode);

    if (el == activeButton)
      return;

    if (getContainerWith(el, "DIV", "menu") == null) {
      resetButton(activeButton);
      activeButton = null;
    }
}

function buttonClick(target, menuId) {
    var button = target;
    button.blur();

    if (button.menu == null) {
        button.menu = document.getElementById(menuId);
        if (button.menu) {
            menuInit(button.menu,target);
        }
    }
    if ((activeButton != null) && (button != activeButton)) {
        resetButton(activeButton);
    }
    if (button != activeButton) {
        depressButton(button);
        activeButton = button;
    }
    return false;
}

function buttonMouseover(target, menuId) {
    var button = target;
    if (activeButton != null && activeButton != button)
        buttonClick(target, menuId);
}

function barMouseOver(target,menuId) {
    var button = target;
    if ((activeButton != null) && (button != activeButton)) {
        if (Prototype.Browser.IE) {
            pushToPosition(document,"");
        }
        removeClassName(activeButton, "menuButtonActive");
        // Hide the button's menu, first closing any sub menus.
        if (activeButton.menu != null) {
            closeSubMenu(activeButton.menu);
            activeButton.menu.style.visibility = "hidden";
            buttonClick(target, menuId);
        }
    }
}

function depressButton(button) {
    var x, y;

    if (Prototype.Browser.IE) {
        pushToPosition(document,-1);
    }
    // Update the button's style class to make it look like it's depressed.
    button.className += " menuButtonActive";
    // Position the associated drop down menu under the button and show it.
    x = getPageOffsetLeft(button);
    y = getPageOffsetTop(button) + button.offsetHeight;
    // For IE, adjust position.
    if (Prototype.Browser.IE) {
        x += button.offsetParent.clientLeft;
        y += button.offsetParent.clientTop;
    }
    if (button.menu) {
        button.menu.style.left = x + "px";
        button.menu.style.top  = y + "px";
        button.menu.style.visibility = "visible";
    }
}

function resetButton(button) {
    if (Prototype.Browser.IE) {
        pushToPosition(document,"");
    }
    removeClassName(button, "menuButtonActive");
    // Hide the button's menu, first closing any sub menus.
    if (button.menu != null) {
        closeSubMenu(button.menu);
        button.menu.style.visibility = "hidden";
    }
}

function pushToPosition(tree,index) {
    if (!tree) {
        return true;
    }
    flag = true;
    if (tree.id == "dest") {
        return false;
    }
    var x = tree.childNodes;
    for (var i=0;i<x.length;i++) {
        if (!pushToPosition(x[i],index)) {
            flag = false;
        }
    }
    if (flag) {
        if (tree.style) {
            var pos = tree.style.position;
            if(pos == "relative" ||
                pos == "absolute" ||
                pos == "fixed") {
                tree.style.zIndex=index
            }
        }
    }
    return flag;
}



function menuMouseover(event,target) {
    var menu = target;
    if (menu.activeItem != null)
        closeSubMenu(menu);
}

function menuLeafMouseOver(event, menuId) {
    var item, x, y;
    if (Prototype.Browser.IE)
        item = getContainerWith(window.event.srcElement, "A", "menuItem");
    else
        item = event.currentTarget;
    menu = getContainerWith(item, "DIV", "menu");
    x = getPageOffsetLeft(menu);
    y = getPageOffsetTop(menu);
    // For IE, adjust position.
    if (Prototype.Browser.IE) {
        x += menu.offsetParent.clientLeft;
        y += menu.offsetParent.clientTop;
    }
    if (Prototype.Browser.IE || Prototype.Browser.Opera )
        window.event.cancelBubble = true;
    else
        event.stopPropagation();
}

function menuItemMouseover(event, menuId) {
    //function menuItemMouseover(target, menuId) {
    var item, menu, x, y;

    if (Prototype.Browser.IE)
        item = getContainerWith(window.event.srcElement, "A", "menuItem");
    else
        item = event.currentTarget;
    menu = getContainerWith(item, "DIV", "menu");

    if (menu.activeItem != null)
        closeSubMenu(menu);
    menu.activeItem = item;

    item.className += " menuItemHighlight";

    if (item.subMenu == null) {
        item.subMenu = document.getElementById(menuId);
        menuInit(item.subMenu,item);
    }
    x = getPageOffsetLeft(item) + item.offsetWidth;
    y = getPageOffsetTop(item);

    var maxX, maxY;

    if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
        maxX = window.scrollX + window.innerWidth;
        maxY = window.scrollY + window.innerHeight;
    }
    if (Prototype.Browser.IE || Prototype.Browser.Opera) {
        if (document.documentElement.clientWidth != 0) {
            maxX = document.documentElement.scrollLeft + document.documentElement.clientWidth;
        }
        else { // FallBack para cuando la pagina no tiene definido el DOCTYPE
            maxX = document.body.scrollLeft + document.body.clientWidth;
        }
        if (document.documentElement.clientHeight != 0) {
            maxY = document.documentElement.scrollTop  + document.documentElement.clientHeight;
        }
        else {
            maxY = document.body.scrollTop  + document.body.clientHeight;
        }
    }
    maxX -= item.subMenu.offsetWidth;
    maxY -= item.subMenu.offsetHeight;
    if (x > maxX)
      x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
        + (menu.offsetWidth - item.offsetWidth));
    y = Math.max(0, Math.min(y, maxY));
    item.subMenu.style.left = x + "px";
    item.subMenu.style.top  = y + "px";
    item.subMenu.style.visibility = "visible";

    if (Prototype.Browser.IE || Prototype.Browser.Opera )
      window.event.cancelBubble = true;
    else
      event.stopPropagation();
}

function closeSubMenu(menu) {
    if (menu == null || menu.activeItem == null)
        return;
    if (menu.activeItem.subMenu != null) {
        closeSubMenu(menu.activeItem.subMenu);
        menu.activeItem.subMenu.style.visibility = "hidden";
        menu.activeItem.subMenu = null;
    }
    removeClassName(menu.activeItem, "menuItemHighlight");
    menu.activeItem = null;
}

function menuInit(menu,item) {
    var itemList, spanList
    var textEl, arrowEl;
    var itemWidth;
    var w, dw;
    var i, j;

    if (Prototype.Browser.IE) {
        menu.style.lineHeight = "2.5ex";
        spanList = menu.getElementsByTagName("SPAN");
        for (i = 0; i < spanList.length; i++)
            if (hasClassName(spanList[i], "menuItemArrow")) {
                spanList[i].style.fontFamily = "Webdings";
                spanList[i].firstChild.nodeValue = "4";
            }
    }
    itemList = menu.getElementsByTagName("A");
    if (itemList.length > 0)
        itemWidth = itemList[0].offsetWidth;
    else
        return;

    for (i = 0; i < itemList.length; i++) {
        spanList = itemList[i].getElementsByTagName("SPAN")
        textEl  = null
        arrowEl = null;
        for (j = 0; j < spanList.length; j++) {
          if (hasClassName(spanList[j], "menuItemText"))
            textEl = spanList[j];
          if (hasClassName(spanList[j], "menuItemArrow"))
            arrowEl = spanList[j];
        }
        if (textEl && arrowEl) {
          textEl.style.paddingRight = (itemWidth 
            - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";
        }
    }
    iframe = document.getElementById(item.padre+"Frame");
    if (iframe) {
        iframe.style.height = menu.offsetHeight + "px";
        iframe.style.width = menu.offsetWidth + "px";
    }
    if (Prototype.Browser.IE) {
        w = itemList[0].offsetWidth;
        itemList[0].style.width = w + "px";
        dw = itemList[0].offsetWidth - w;
        w -= dw;
        itemList[0].style.width = w + "px";
    }
}

function getContainerWith(node, tagName, className) {
    while (node != null) {
      if (node.tagName != null && node.tagName == tagName &&
          hasClassName(node, className))
        return node;
      node = node.parentNode;
    }

    return node;
}

function hasClassName(el, name) {
    var i, list;
    list = el.className.split(" ");
    for (i = 0; i < list.length; i++)
      if (list[i] == name)
        return true;

    return false;
}

function removeClassName(el, name) {
    var i, curList, newList;
    if (el.className == null)
      return;
    newList = new Array();
    curList = el.className.split(" ");
    for (i = 0; i < curList.length; i++)
      if (curList[i] != name)
        newList.push(curList[i]);
    el.className = newList.join(" ");
}

function getPageOffsetLeft(el) {
    var x;
    x = el.offsetLeft;
    var dest = document.getElementById("dest");
	if (dest.style.position != "absolute") {
	    if (el.offsetParent != null)
	      x += getPageOffsetLeft(el.offsetParent);
	}
    return x;
}

function getPageOffsetTop(el) {
    var y;
    y = el.offsetTop;
	var dest = document.getElementById("dest");
	if (dest.style.position != "absolute") {
	    if (el.offsetParent != null)
	      y += getPageOffsetTop(el.offsetParent);
	}
    return y;
	
}
